package com.jams.goodox.activity.mine.download;

import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.login.RoleInfoUploadActivity;
import com.jams.goodox.activity.qa.GlideCircleTransform;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.db.DBManager;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;

/**
 * Created by Administrator on 2018/5/12.
 */

public class MyDownloadActivity extends BaseActivity implements OnItemClickListener,
        LFRecyclerView.LFRecyclerViewListener{
    private static final String TAG = "MyDownloadActivity";
    @Bind(R.id.recycle_view)
    LFRecyclerView recycleView;

    private List<DownloadBean> downloadBeenList;
    private CommonRecycleViewAdapter pAdapter;

    private boolean tag1 = false;
    private boolean tag2 = false;

    public MediaPlayer mediaPlayer;
    public boolean tag = false;

    @Bind(R.id.bottom_layout)
    RelativeLayout bottom_layout;

    @Bind(R.id.imageView)
    ImageView imageView;

    @Bind(R.id.title)
    TextView title;

    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.play_menu)
    TextView play_menu;

    private int playPosition= -100;


    @Override
    protected int getLayoutId() {
        return R.layout.mine_download_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"我的下载");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部

        final int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.margin_size_small);
        recycleView.addItemDecoration(new ItemDecoration(){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = spacingInPixels;
            }
        });

        recycleView.setFootText("");
        recycleView.setLoadMore(false);
        recycleView.setRefresh(false);
        recycleView.setNoDateShow();
        recycleView.setAutoLoadMore(false);
        recycleView.setOnItemClickListener(this);
        recycleView.setLFRecyclerViewListener(this);
        //recyclerView.setScrollChangeListener(this);
        recycleView.setItemAnimator(new DefaultItemAnimator());

        downloadBeenList= DBManager.getInstance(this).queryDownList();


        Log.d(TAG,"downloadBeenList = " + downloadBeenList.toString());

        pAdapter = new CommonRecycleViewAdapter(recycleView,downloadBeenList,R.layout.mine_download_item){

            @Override
            public void bindConvert(LFRecyclerViewHolder holder, final int position, Object item, boolean isScrolling) {
                final DownloadBean bean = (DownloadBean) item;
                holder.loadImage(R.id.imageView,bean.getPic());
                holder.setText(R.id.title,bean.getTitle());
                holder.setText(R.id.name,bean.getName());

                final ImageView play_btn = holder.getView(R.id.play_btn);
                if(bean.isPlaying()){
                    Log.d(TAG,"-----------播放 = " + position);
                    play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                }else {
                    Log.d(TAG,"-----------暂停 = " + position);
                    play_btn.setImageResource(R.mipmap.wodexiazai_bofang);
                }

                play_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(new File(bean.getUrl()).exists()){
                            //bottom_layout.setVisibility(View.VISIBLE);
                        }else {
                            //bottom_layout.setVisibility(View.GONE);
                            return;
                        }
//                        Glide.with(MyDownloadActivity.this).load(bean.getPic())
//                                .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
//                                .error(R.mipmap.morentouxiang60) //失败图片
//                                .bitmapTransform(new GlideCircleTransform(MyDownloadActivity.this))
//                                .crossFade(1000).into(imageView);
//                        title.setText(bean.getTitle());
//                        name.setText(bean.getName());
//                        play_menu.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                if(mediaPlayer != null){
//                                    if(mediaPlayer.isPlaying()){
//                                        mediaPlayer.stop();
//                                        play_menu.setText("停止播放");
//                                    }else {
//                                        setMedia(bean.getUrl(), play_btn );
//                                        mediaPlayer.start();
//                                        play_menu.setText("正在播放");
//                                    }
//                                }
//                            }
//                        });


                        if(playPosition == -100){//第一次打开页面 播放
                            setMedia(bean.getUrl(), play_btn );
                            playOrPause( );
                            play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                            playPosition = position;
                            return;

                        }

                        if(playPosition == position){
                            setMedia(bean.getUrl(), play_btn );
                            if (mediaPlayer.isPlaying()) {
                                play_btn.setImageResource(R.mipmap.wodexiazai_bofang);
                                mediaPlayer.stop();
                                Log.d(TAG,"-----------暂停播放 = " + position);
                            } else {
                                mediaPlayer.start();
                                play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                                Log.d(TAG,"-----------重新播放 = " + position);
                            }
                            //playOrPause( );
                            return;
                        }

                        if(/*playPosition!= -100 &&*/ playPosition != position){
                            playPosition = position;
                            if (mediaPlayer.isPlaying()) {
                                //如果之前的在播放
                                mediaPlayer.stop();
                                setMedia(bean.getUrl(), play_btn );
                                updateOtherStatus(position);
                                play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                                mediaPlayer.start();
                                Log.d(TAG,"-----------上一个正在播放，现在切换播放 = " + position);
                            } else {
                                //如果之前的播放已经停止，不需要额外处理
                                setMedia(bean.getUrl(), play_btn );
                                play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                                mediaPlayer.start();
                                Log.d(TAG,"-----------上一个已经暂停，现在播放 = " + position);
                            }
                            //把之前的播放状态都设置为

                        }

                    }

                });
            }
        };

        recycleView.setAdapter(pAdapter);

    }

    private void updateOtherStatus(int pos) {

        for(int i = 0; i < downloadBeenList.size();i++){
            if(pos == i){
                downloadBeenList.get(i).setPlaying(true);
            }else {
                downloadBeenList.get(i).setPlaying(false);
            }
        }

        Log.d(TAG,"downloadBeenList = " + downloadBeenList.toString());

        pAdapter.notifyDataSetChanged();
    }


    private void setMedia(final String radioLink, final ImageView play_btn ) {
        if(null == mediaPlayer){
            mediaPlayer = new MediaPlayer();
            //mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mediaPlayer.setDataSource(radioLink);
                mediaPlayer.prepare();
                mediaPlayer.setLooping(false);
//                play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else {
            try {
                //mediaPlayer.reset();
                if(mediaPlayer.isPlaying()){
//                    play_btn.setImageResource(R.mipmap.wodexiazai_bofang);
                    mediaPlayer.stop();
                }else {
//                    play_btn.setImageResource(R.mipmap.wodexiazai_zanting);
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(radioLink);
                    mediaPlayer.prepare();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if(TextUtils.isEmpty(radioLink)){
                    play_btn.setImageResource(R.mipmap.wodexiazai_bofang);
                    ToastUtil.show("获取音频文件失败");
                    return;
                }
                //playOrPause();
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //ToastUtil.show("播放结束");
                play_btn.setImageResource(R.mipmap.wodexiazai_bofang);
                Log.d(TAG,  "播放结束" );
            }
        });

//        playOrPause();
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume = " );
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause = " );
        updateOtherStatus(-1);//页面后台运行的时候，修改播放状态
        stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }

    public void playOrPause() {
        if (mediaPlayer.isPlaying()) {
            play_menu.setText("停止播放");
            mediaPlayer.stop();
        } else {
            mediaPlayer.start();
            play_menu.setText("正在播放");
        }
    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    public void release(){
        if(mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onLongClick(int po) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }
}
